package org.example.controller.actualCombat;

import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.downloader.Downloader;
import us.codecraft.webmagic.selector.PlainText;

import java.util.List;

@Component
public class PlaneDownloader implements Downloader {


    private RemoteWebDriver driver;

    //   构造方法中初始化无头浏览器
    public PlaneDownloader() throws InterruptedException {
        //创建配置信息
        System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\Google\\Chrome\\Application\\chromedriver.exe");
        ChromeOptions chromeOptions = new ChromeOptions();
//        所在headless模式（必须）  无头模式
//        chromeOptions.addArguments("--headless");
//        设置浏览器窗口的大小（非必填）
        chromeOptions.addArguments("--window-size=1366,700");
//        4.基于配置对象创建RemoteWebDriver对象
        driver = new ChromeDriver(chromeOptions);
        driver.get("https://web.telegram.org/a/");
        Thread.sleep(20000);
        driver.findElementByXPath("//*[@id=\"auth-qr-form\"]/div/button[1]").click();
        Thread.sleep(2000);
        driver.findElementByCssSelector("#sign-in-phone-number").clear();
        driver.findElementByCssSelector("#sign-in-phone-number").sendKeys("+639683443418");
        Thread.sleep(2000);
        driver.findElementByXPath("//*[@id=\"auth-phone-number-form\"]/div/form/button[1]").click();
        Thread.sleep(5000);
    }


    @Override
    public Page download(Request request, Task task) {
        try {
            //载页面的业务逻辑
            String url = request.getUrl();
//        从request对象中取要访问的url
            if (!"http://nextpage.com".equals(url)) {
                driver.get(url);
                driver.findElementByXPath("//*[@id=\"LeftColumn-main\"]/div[2]/div/div/div/div/div[2]/div[2]").click();
                driver.findElementByXPath("//*[@id=\"LeftColumn-main\"]/div[2]/div/div/div/div").click();
                driver.findElementByXPath("//*[@id=\"MiddleColumn\"]/div[4]/div[2]/div/div[1]/div/div[2]").click();
                Thread.sleep(2000);
                driver.findElementByCssSelector("#MiddleColumn > div.messages-layout > div.Transition > div > div.MessageList.custom-scroll.with-default-bg.scrolled > div > div.message-date-group").sendKeys(Keys.PAGE_UP);
                List<WebElement> list = driver.findElementsByCssSelector("#message403765 div");
                if (list.size() > 0) {
                    driver.executeScript("window.scrollTo(0,document.body.scrollHeight -300)");
                    Thread.sleep(2000);
//          从浏览器中取html
                    String html = driver.getPageSource();
                    //        需要把结果封装为Page对象
                    Page page = createPage(html, driver.getCurrentUrl());
                    return page;
                }
                String html = driver.getPageSource();
                Page page = createPage(html, driver.getCurrentUrl());
                return page;
            } else {
//                   3如果是翻页处理
//                从request对象中取附件翻页之前的url
                String curUrl = request.getExtra("url");
                driver.get(curUrl);
//                点击翻页按钮 翻到第二页
                driver.findElementByCssSelector("#pagelink > a:nth-child(13)").click();
                Thread.sleep(2000);
                driver.executeScript("window.scrollTo(0,document.body.scrollHeight -300)");
                Thread.sleep(2000);
                String html= driver.getPageSource();
                Page page = createPage(html, driver.getCurrentUrl());
                return page;
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void setThread(int i) {

    }

    //将html封装成Page对象
    private Page createPage(String html, String url) {
        Page page = new Page();
        page.setRawText(html);
        page.setUrl(new PlainText(url));
//        设置一个request对象
        page.setRequest(new Request(url));
//        设置抓取成功的标志
        page.setDownloadSuccess(true);
        return page;

    }
}
